<?php

class Service_UserModel {

    private $_userDao;
    private $_sessionSvc;
    private $_userLoginDao;
    private $_userSetDao;
    private $_userRechargeDao;
    private $_userConsumeDao;

    const USER_VCODE_KEY  = '_xd_xiaoshuo';
    const USER_NORMAL_STATUS = 1;
    const USER_LOGIN_STATUS  = '_USER_LOGIN_STATUS';
    const USER_INFO = 'USER:INFO_KEY_';

    public function __construct ()
    {
        $this->_userDao         = new Dao_UserModel();
        $this->_sessionSvc      = new Service_SessionModel();
        $this->_userLoginDao    = new Dao_UserLoginModel();
        $this->_userSetDao      = new Dao_UserSetModel();
        $this->_userRechargeDao = new Dao_UserRechargeModel();
        $this->_userConsumeDao  = new Dao_UserConsumeModel();
    }
    
    const MSG_SIGN = "【享点小说】";
    const MSG_TPL = "验证码为：#code#（5分钟内有效），请尽快完成验证。如非本人操作，请忽略该短信。";
    const MSG_RESETPASSWORD_TPL = "您正在找回密码，验证码是#code#（2分钟内有效）。如非本人操作，请忽略该短信。";
    
    public function getDynamicCode( $ip , $phone, $scene = 1 ){
        switch ($scene){
            case 1:
                $msg = self::MSG_SIGN.self::MSG_TPL;
                break;
            case 2:
                $msg = self::MSG_SIGN.self::MSG_RESETPASSWORD_TPL;
                break;
            default:
                break;
        }
        
        $sms = new Sms();
        $res = $sms->singleSend( $phone , $msg , $ip );
        return $res;
    }
    
    /**
     * 获取图片验证码
     * @param type $phone
     * @return type
     */
    public function getIImgCode( ){
        $img = new VerifyCode(); 
        $img->doimg();
        $code = $img->getCode();
        $_SESSION['imgCode'] = $code;
    }

    /*
     * 登陆
     * @param $mobile 
     * @param $password 
     * @param $usertype 用户类型
     */

    public function login ($mobile = '' , $password = '' , $vcode = '' , $ua = 'unknown')
    {
        //参数不正确
        if ( '' == $mobile || '' == $vcode || '' == $password ) {
            return [ 'msg' => YExceptionTool::getMsg(YExceptionTool::PARAMPACK_ERROR) ];
        }
        //验证码
        $redis_tool = RedisTool::getInstance();
        $code = $redis_tool->get( $mobile.self::USER_VCODE_KEY );
        LogTool::errorlogLog()->log($mobile);
        if( $code != $vcode ){
            return [ 'msg' => YExceptionTool::getMsg(YExceptionTool::VCODE_ERROR) ];
        }
        $where                    = array ();
        $where[ 'user_phone' ]    = $mobile;
        $where[ 'user_password' ] = $password;
        $info                     = $this->_userDao->getUserInfo ( $where );
        
        $time = date('Y-m-d H:i:s');
        //用户不存在,新增用户
        if ( ! $info ) {
            $new_data                           = array ();
            $new_data['user_phone']             = $mobile;
            $new_data['user_create_time']       = $time;
            $new_data['user_last_login_time']   = $time;
            $new_data['user_reg_time']          = $time;
            $uid                    = $this->_userDao->addUser($new_data);
            if($uid){
                $info = [
                    'user_phone'    => $mobile,
                    'user_id'       => $uid,
                    'user_nickname' => '',
                    'user_sex'      => 0,
                    'user_age'      => 0,
                    'user_address'  => '',
                    'user_create_time' => $time,
                    'user_last_login_time' => $time,
                    'user_reg_time' => $time,
                    'user_img_url'  => '',
                ];
            }else{
                return [ 'msg' => '登录失败请重试' ];
            }
        }else{
            $this->_userDao->editUser( [ 'user_last_login_time' => $time ] , [ 'user_id' , $info['user_id'] ]  );
        }
        $id = $info['user_id'];
        //生成token
        $sessionid   = md5($ua) . $id . 'LOGIN';
        setcookie( 'USELF' , base64_encode($sessionid) , time()+3600*24*7 , "/" , '' , false , true );
        $redis_tool->set( $sessionid , $id , 3600*24*7 );
        if( $info ){
            return $info;
        }else{
            return [ 'msg' => '登录失败请重试' ];
        }
    }
    
    /**
     * 添加登录日志
     */
    public function addLog( $data = [] )
    {
        if( $data ){
            $res = $this->_userLoginDao->addLog($data);
            return $res;
        }
        return FALSE;
    }
    
    /**
     * 获取用户信息
     * @param type $uid
     */
    public function getUserInfo( $uid )
    {
        $info = $this->_userDao->getUserInfo( [ 'user_id' => $uid ] );
        return $info ? $info : false;
    }
    
    /**
     * 获取用户密码
     * @param type $uid
     */
    public function getUserPwd( $uid )
    {
        $info = $this->_userDao->getUserPwd( [ 'user_id' => $uid ] );
        return $info ? $info : false;
    }
    
    /**
     * 修改用户信息
     */
    public function updateUser( $uid , $type = '' , $d = '' )
    {
        $res = false;
        if( !$uid ){
            return false;
        }
        
        if( $type == 'phone' ){
            $mobileReg = '/1[3|4|5|7|8]\d{9}$/';
            if(!preg_match ( $mobileReg , $d ) || trim($d) == ''){
                return false;
            }
        }
        if( $type == 'name' ){
            if( mb_strlen(htmlspecialchars($d),'UTF-8') > 20 ){
                return false;
            }
        }
        if( $type != '' ){
            $column = '';
            $update = '';
            $data = array ();
            switch ( $type ) {
                case 'name':
                    $column = 'user_nickname';
                    $update = htmlspecialchars($d);
                    $data[$column] = $update;
                    break;
                case 'sex':
                    $column = 'user_sex';
                    $update = in_array(htmlspecialchars($d),['1','2']) ? htmlspecialchars($d) : 0;
                    $data[$column] = $update;
                    break;
                case 'age':
                    $column = 'user_age';
                    $update = intval($d) >= 0 ? intval($d) : 0;
                    $data[$column] = $update;
                    break;
                case 'address':
                    $column = 'user_address';
                    $data['user_province'] = $d[0];
                    $data['user_city']     = $d[1];
                    $data['user_area']     = $d[2];
                    break;
                case 'phone':
                    $column = 'user_phone';
                    $update =  $d;
                    $data[$column] = $update;
                    break;
                case 'image':
                    $column = 'user_img_url';
                    $update =  $d;
                    $data[$column] = $update;
                    break;
                default :
                    break;
            }
            $res = $this->_userDao->editUser( $data , array ( [ 'user_id' , $uid ] ) );
            if($res){
                $redis = RedisTool::getInstance();
                $info = $redis->get( self::USER_INFO.$uid );
                if(!$info){
                    $datas = $this->_userDao->getUserInfo( [ 'user_id' => $uid ] );
                }else{
                    $datas = json_decode( $info , true );
                    if($type == 'address'){
                        $datas['user_province'] = $d[0];
                        $datas['user_city']     = $d[1];
                        $datas['user_area']     = $d[2];
                    }else{
                        $datas[$column] = $update;
                    }
                }
                $redis->set( self::USER_INFO.$uid , json_encode( $datas ) );
                unset( $info , $datas );
            }
        }
        
        return $res;
    }
    
    /**
     * 修改用户设置
     */
    public function editUserSet( $uid = 0 , $back = '' , $size = 0 , $style = 0 )
    {
        if( !$uid ){
            return false;
        }
        $set = $this->getUserSet($uid);
        if($set){
            if( $set['set_fontsize'] == $size && $set['set_back'] == $back && $set['set_style'] == $style ){
                return false;
            }
        }
        $r = $this->_userSetDao->delSet( array ( array ( 'set_user_id' , $uid ) ) );
        if( !$r ){
            return false;
        }
        $data = [
            'set_user_id'  => $uid,
            'set_fontsize' => $size,
            'set_back'     => $back == 'night' ? 4 : $back,
            'set_style'    => $style,
        ];
        $res = $this->_userSetDao->addSet($data);
        return $res;
    }
    
    /**
     * 获取用户设置
     */
    public function getUserSet( $uid = 0 )
    {
        if( !$uid ){
            return [
                'set_id'       => 0,
                'set_user_id'  => 0,
                'set_fontsize' => 36,
                'set_back'     => 3,
                'set_style'    => 1,
            ];
        }
        $where['set_user_id'] = $uid;
        $sets = $this->_userSetDao->getSet($where);
        return $sets;
    }
    
    /**
     * 用户充值记录
     */
    public function getUserRecharge( $uid )
    {
        if( !$uid ){
            return [];
        }
        $list = $this->_userRechargeDao->getUserRecharge( $uid );
        foreach($list as $key=>$val){
            switch( $val['pay_type'] ){
                case 1:
                    $list[$key]['pay_type'] = '支付宝';
                    break;
                case 2:
                    $list[$key]['pay_type'] = '微信';
                    break;
                case 3:
                    $list[$key]['pay_type'] = '银联';
                    break;
                case 4:
                    $list[$key]['pay_type'] = '其他';
                    break;
                default :
                    $list[$key]['pay_type'] = '未知';
                    break;
            }
        }
        return $list ? $list : [];
    }
    
    /**
     * 用户消费记录
     */
    public function getUserConsume( $uid )
    {
        if( !$uid ){
            return [];
        }
        $list = $this->_userConsumeDao->getUserConsume( $uid );
        $nids = array_column( $list , 'novel_id' );
        $novelModel = new Dao_NovelModel();
        $novels = $novelModel->getNovelList( array( 'novelids' => array( 'novel_id' , $nids ) ) , 'no');
        $n_k_v = array_column( $novels , null , 'novel_id' );
        foreach( $list as $k=>$v ){
            $list[$k]['novel'] = isset( $n_k_v[ $v[ 'novel_id' ] ] ) ? $n_k_v[ $v[ 'novel_id' ] ][ 'novel_title' ] : '未知';
        }
        return $list ? $list : [];
    }
    /**
     * 用户消费某本小说记录
     */
    public function getUserNovelConsume( $uid,$novelid,$chapterid )
    {
        if( !$uid && !$novelid && !$chapterid){
            return [];
        }
        $list = $this->_userConsumeDao->getUserNovelConsume( $uid , $novelid , $chapterid);
        return $list ? $list : [];
    }
    
    /*
     * 生成Sid  也就是token 
     */

    private static function buildSid ()
    {
        $id_main = date ( 'YmdHis' ) . rand ( 1000 , 9999 );
        $id_len  = 10;
        $id_sum  = 0;
        for ( $i = 0; $i < $id_len; $i ++ )
        {
            $id_sum += ( int ) (substr ( $id_main , $i , 1 ));
        }
        return $id_main . str_pad ( (100 - $id_sum % 100) % 100 , 2 , '0' , STR_PAD_LEFT );
    }
    
     /**
     * 获取用户是否注册
     * @param type $uid
     */
    public function verifyPhone( $phone )
    {
        $info = $this->_userDao->verifyPhone( [ 'user_phone' => $phone ] );
        return $info;
    }
    
    
    /**
     * 验证图片验证码
     * @param bool 
     */
    public function verifyImgCode($imgCode )
    {
        $localImgCode = $_SESSION['imgCode'];
        $res = $imgCode == $localImgCode ? true : false;
        return $res;
    }
    
    
    /*
     * 注册
     * @param $mobile 
     * @param $password 
     * @param $usertype 用户类型
     */

    public function register ($mobile = '' , $password = '', $ua = 'unknown'){
        $new_data = [];
        $new_data['user_uuid'] = create_uuid();
        $new_data['user_nickname'] = 'XS' . substr($mobile, -4);
        $new_data['user_password'] = password_hash($password, PASSWORD_DEFAULT);
        $new_data['user_type']             = 1;
        $new_data['user_phone']             = $mobile;
        $new_data['user_create_time']       = date('Y-m-d H:i:s');
        $new_data['user_last_login_time']   = date('Y-m-d H:i:s');
        $new_data['user_reg_time']          = date('Y-m-d H:i:s');
        $res = $this->_userDao->addUser($new_data);
        return $res;
    }
    
    /**
     * 忘记密码,重置密码
     */
    public function resetPassword($mobile,$password){
        $new_data = [];
        $where = [];
        $where[] = array('user_phone',$mobile);
        $new_data['user_password'] = password_hash($password, PASSWORD_DEFAULT);
        $res = $this->_userDao->editUser($new_data,$where);
        return $res;
    }
    
    public function resetPasswordById($uid,$password)
    {
        $new_data = [];
        $where = [];
        $where[] = array('user_id',$uid);
        $new_data['user_password'] = password_hash($password, PASSWORD_DEFAULT);
        $res = $this->_userDao->editUser($new_data,$where);
        return $res;
    }
    
    
}
